'use strict';

const Service = require('egg').Service;
const crypto = require('crypto');

// 设置默认密码
const DEFAULT_PWD = '123456';
function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class UserService extends Service {
  // 查询user表，验证密码和花名
  async validUser(nickname, password) {
    const data = await this.getUser();
    const pwd = crypto.createHash('md5').update(password).digest('hex');
    for (const item of data) {
      if (item.nickname === nickname && item.password === pwd) return true;
    }
    return false;
  }

  // 获取用户，不传id则查询所有
  async getUser(id) {
    const { ctx } = this;
    const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) };
    
    if (id) {
      return await ctx.model.UserDB.findByPk(toInt(id));
    }
    return await ctx.model.UserDB.findAll(query);
  }

  // 新增人员
  async addUser(nickname) {
    const { ctx } = this;
    const password = this.getMd5Data(DEFAULT_PWD);
    await ctx.model.UserDB.create({ nickname, password });
  }
  // 修改密码
  async editPwd(id, password) {
    const { ctx } = this;
    const user = await ctx.model.UserDB.findByPk(id);
    const newPwd = this.getMd5Data(password);
    await user.update({ password: newPwd });
  }

  // 专门对数据进行md5加密的方法，输入明文返回密文
  getMd5Data(data) {
    return crypto.createHash('md5').update(data).digest('hex');
  }
}
module.exports = UserService;
